<template>
  <div>
    <a-card :body-style="{padding: '24px 32px'}" :bordered="false">
      <a-form
        :form="form"
        @submit="handleSubmit">

        <a-form-item
          label="请选择商品分类"
          :label-col="{ span: 5 ,offset: 4}"
          :wrapper-col="{ span: 7 }"
        >
          <a-checkbox-group :options="plainOptions" v-model="checkedList" @change="onChange"></a-checkbox-group>
        </a-form-item>
        <a-form-item
          label="商品名称"
          :label-col="{ span: 5 ,offset: 4}"
          :wrapper-col="{ span: 7 }"
        >
          <a-input
            v-decorator="[
              'name',
              {rules: [{ required: true, message: '请输入商品名称!!' }]}
            ]"
            placeholder="请输入商品名称..."
          ></a-input>
        </a-form-item>
        <a-form-item
          label="商品价格"
          :label-col="{ span: 5 ,offset: 4}"
          :wrapper-col="{ span: 7 }"
        >
          <a-input
            v-decorator="[
              'price',
              {rules: [{ required: true, message: '请输入商品价格!!' }]}
            ]"
            placeholder="请输入商品价格..."
          ></a-input>
        </a-form-item>
        <a-form-item
          label="库存量"
          :label-col="{ span: 5 ,offset: 4}"
          :wrapper-col="{ span: 7 }"
        >
          <a-input
            v-decorator="[
              'stock',
              {rules: [{ required: true, message: '请输入商品库存量!!' }]}
            ]"
            placeholder="请输入商品库存量..."
          ></a-input>
        </a-form-item>
        <a-form-item
          label="销量"
          :label-col="{ span: 5 ,offset: 4}"
          :wrapper-col="{ span: 7 }"
        >
          <a-input
            v-decorator="[
              'sales_volume',
              {rules: [{ required: true, message: '请输入商品销量!!' }]}
            ]"
            placeholder="请输入商品销量..."
          ></a-input>
        </a-form-item>
        <a-form-item
          label="产品图片"
          :label-col="{ span: 5 ,offset: 4}"
          :wrapper-col="{ span: 7 }"
        >
          <div class="clearfix">
            <a-upload
              :fileList="fileList"
              :remove="handleRemove"
              :beforeUpload="beforeUpload"
              @change="handleUpload"
            >
              <a-button>
                <a-icon type="upload"></a-icon> 选择图片
              </a-button>
            </a-upload>
            <!--<a-button
              type="primary"
              @click="handleUpload"
              :disabled="fileList.length === 0"
              :loading="uploading"
              style="margin-top: 16px"
            >
              {{ uploading ? '上传中' : '开始上传' }}
            </a-button>-->
            <div class="banner_img" style="display: flex; " v-if="GoodsImageArr.length>0">
              <div style="margin: 10px 10px 10px 0;display: flex;" v-for="(img, index) in GoodsImageArr" :key="index">
                <img :src="'https://admin.muyumall.com'+img.img_url" alt="" height="80px">
                <div style="cursor: pointer" @click="delImg(index)"><a-icon type="delete" ></a-icon>
                </div>
              </div>
            </div>
          </div>
        </a-form-item>
        <a-form-item
          label="产品图文"
          :label-col="{ span: 5 ,offset: 4}"
          :wrapper-col="{ span: 7 }"
        >
          <!--<a-textarea placeholder="Basic usage" :rows="4"></a-textarea>-->
          <a-button type="primary" @click="showModal">编辑</a-button>
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 12, offset: 9 }">
          <a-button
            type="primary"
            html-type="submit"
          >
            保存
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>
    <a-modal
      title="Modal"
      v-model="visible"
      width="60%"
      @ok="saveHtml"
      okText="确认"
      cancelText="取消"
    >
      <quill-editor
        v-model="content"
        ref="myQuillEditor"
        :options="quillConfig"
        @blur="onEditorBlur($event)"
        @focus="onEditorFocus($event)"
        @change="onEditorChange($event)">
      </quill-editor>

    </a-modal>
  </div>
</template>

<script>
import { queryCategory } from '@/api/goodsCategory'
import { uploadGoodsImg, goodsSave, queryGoods } from '@/api/goods'
import quillConfig from '../../config/quill-config.js'

export default {
  name: 'EditGoods',
  components: {
  },
  data: function () {
    return {
      id: '',
      serial_no: 1,
      GoodsImageArr: [], // 图片
      file: '',
      content: '', // 富文本
      quillConfig,
      visible: false,
      uploading: false,
      categoryArr: [],
      plainOptions: [],
      checkedList: [],
      previewVisible: false,
      previewImage: '',
      fileList: []
    }
  },
  beforeCreate () {
    this.form = this.$form.createForm(this)
  },
  computed: {
    editor: function () {
      return this.$refs.myQuillEditor.quill
    }
  },
  mounted () {
    // 获取商品信息
    const id = this.$route.query.id
    this.getGoodById(id)

    // 获取分类
    queryCategory({}).then((res) => {
      this.categoryArr = res
      res.forEach((v) => {
        this.plainOptions.push(v.name)
      })
    })
      .catch((err) => {
        console.log(err)
      })
  },
  methods: {
    delImg (index) {
      this.GoodsImageArr.splice(index, 1)
    },
    // 根据id查询商品
    getGoodById (id) {
      const _this = this
      queryGoods({ id })
        .then(res => {
          console.log(res)
          const { form } = _this
          form.setFieldsValue({
            name: res.name,
            price: res.price,
            stock: res.stock,
            sales_volume: res.sales_volume
          })
          res.goods_class_infos.forEach(v => {
            this.checkedList.push(v.name)
          })
          console.log(_this.checkedList)

          _this.content = res.details
          _this.GoodsImageArr = res.goods_img_infos
        })
        .catch(err => {
          console.log(err)
        })
    },
    handleRemove (file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },
    showModal () {
      this.visible = true
    },
    handleUpload: function () {
      const { fileList } = this
      const formData = new FormData()
      console.log(666, fileList)
      formData.append('file', fileList[fileList.length - 1])
      this.uploading = true
      console.log(formData)
      uploadGoodsImg(formData)
        .then((res) => {
          console.log(res)
          const GoodsImage = {
            img_url: res[0].url,
            serial_no: this.serial_no
          }
          this.GoodsImageArr.push(GoodsImage)
          this.serial_no++
          this.uploading = false
          this.$message.success('上传成功！')
        })
        .catch((err) => {
          console.log(err)
          this.uploading = false
          this.$message.error('上传失败！')
        })
    },
    beforeUpload (file) {
      console.log(file)
      this.fileList = [...this.fileList, file]
      return false
    },
    onChange (items) {
      console.log(items)
      console.log(this.categoryArr)
      items.forEach((item) => {
        this.categoryArr.forEach((category) => {
          if (category.name === item) {
            this.id = category.id
          }
        })
      })
    },
    handleCancel () {
      this.previewVisible = false
    },
    handlePreview (file) {
      this.previewImage = file.url || file.thumbUrl
      this.previewVisible = true
    },
    handleChange ({ fileList }) {
      this.fileList = fileList
    },
    addStyle (Str) {
      let strArr = []
      let newStr = ''
      strArr = Str.split('<img')
      for (let i = 0; i < strArr.length; i++) {
        if (i !== 0) {
          strArr[i] = '<img style=\'max-width:100%;height:auto;margin-top:-10px;\' ' + strArr[i]
        }
        newStr += strArr[i]
      }
      return newStr
    },
    // 保存
    handleSubmit (e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          if (this.checkedList === []) {
            this.$message.warning('请选择商品分类')
            return false
          }
          if (this.content === '') {
            this.$message.warning('请填写商品详情图文')
            return false
          }
          if (this.GoodsImageArr === []) {
            this.$message.warning('请上传产品图片')
            return false
          }
          values.goods_class_infos = []
          this.checkedList.forEach((item) => {
            this.categoryArr.forEach((category) => {
              if (category.name === item) {
                values.goods_class_infos.push(category)
              }
            })
          })
          values.details = this.addStyle(this.content)
          values.goods_images = this.GoodsImageArr
          values.id = this.$route.query.id
          values.upper_shelf_states = this.$route.query.upper_shelf_states
          values.recommend_states = this.$route.query.recommend_states

          console.log(values)
          goodsSave(values)
            .then((res) => {
              if (res) { this.$message.success('编辑商品成功！') }
              this.$router.push({ path: 'goods-list' })
              console.log(res)
            })
            .catch((err) => {
              console.log(err)
              this.$message.error('编辑商品失败！')
            })
        }
      })
    },
    onEditorReady (editor) { // 准备编辑器
    },
    onEditorBlur () {}, // 失去焦点事件
    onEditorFocus () {}, // 获得焦点事件
    onEditorChange () {}, // 内容改变事件
    saveHtml (event) {
      console.log(this.content)
      this.visible = false
    }
  }
}
</script>
<style scoped lang="less"></style>
